package ferp.core.ai.strategy.simple;

import ferp.core.ai.strategy.Contracting;
import ferp.core.calc.Calculator;
import ferp.core.game.Bid;
import ferp.core.game.Game;
import ferp.core.game.Input;
import ferp.core.game.Settings;
import ferp.core.player.AI;

/**
 * User: igorgok
 * Date: 5/30/11 1:24 PM
 */
public class SimpleContracting extends Contracting
{
  @Override
  public Bid tricks(int cards, boolean starting)
  {
    return Estimate.tricks(cards, starting);
  }

  @Override
  public Bid whists(Game g, Settings settings, AI ai)
  {
    Bid contract = g.getDeclarerBid().current;
    int esw = Calculator.getExpectedStandingWhists(contract.tricks);
    int whists = Estimate.whists(ai, g.getHand(ai.id()).current, contract.trump);
    int whistsInTrump = Estimate.whistsInTrump(ai, g.getHand(ai.id()).current, contract.trump);

    switch (g.hand)
    {
      case 1:
        // the partner is half whister - it is enough to have at least expected standing whists
        if (g.player.half != Game.NO_ID)
          if (whists >= esw)
            return Bid.whist(whists);

        return tryToWhist(contract.tricks, whistsInTrump, whists);

      case 2:
        // first check if whist can be played - the 'whist' option is always set for the player
        Bid w = tryToWhist(contract.tricks, whistsInTrump, whists);

        if (w.isWhist())
          return w;

        // if 'half-whist' option is set that means the partner said 'pass'
        if (g.options.isSet(Input.Options.WHIST_HALF))
          return Bid.halfWhist(whists);

        // otherwise try to 'whist' having less tricks than required for open game since partner said 'whist'
        switch (contract.tricks)
        {
          case 6:
          case 7:
            if (whists >= esw)
              return Bid.whist(whists);

            break;

          default:
            if (whistsInTrump > 0)
              return Bid.whist(whistsInTrump);
        }

        break;

      default:
        // should never get here
        assert false: "hand must be either 1 or 2";
    }

    // pass
    return Bid.pass();
  }

  private static Bid tryToWhist(int contract, int whistsInTrump, int whists)
  {
    switch (contract)
    {
      case 6:
        if (whists >= 3)
          return Bid.whist(whists);

        break;

      case 7:
        if (whists >= 2)
          return Bid.whist(whists);

        break;

      case 8:
        if (whistsInTrump >= 1 || whists >= 2)
          return Bid.whist(whists);

        break;

      case 9:
      case 10:
        if (whistsInTrump >= 1 || whists >= 3)
          return Bid.whist(whists);

        break;
    }

    return Bid.pass();
  }
}
